package com.ikunkun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikunkun.constant.MessageConstant;
import com.ikunkun.constant.PasswordConstant;
import com.ikunkun.constant.StatusConstant;
import com.ikunkun.context.BaseContext;
import com.ikunkun.dto.EmployeeDTO;
import com.ikunkun.dto.EmployeeLoginDTO;
import com.ikunkun.dto.EmployeePageQueryDTO;
import com.ikunkun.entity.Employee;
import com.ikunkun.exception.AccountLockedException;
import com.ikunkun.exception.AccountNotFoundException;
import com.ikunkun.exception.PasswordErrorException;
import com.ikunkun.mapper.EmployeeMapper;
import com.ikunkun.result.PageResult;
import com.ikunkun.result.Result;
import com.ikunkun.service.EmployeeService;

import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
@Transactional
public class EmployeeLoginImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Resource
    private EmployeeMapper employeeMapper;

    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        Employee employee = employeeMapper.getByUsername(username);
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 密码比对
        // 在使用Spring框架的时候，我们会对一些重要的密码进行加密可以使用MD5，其工具类是DigestUtils
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        // 3、返回实体对象
        return employee;
    }

    @Override
    public Result<PageResult> pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        // 创建Page对象，设置当前页和每页显示记录数
        Page<Employee> pageInfo = new Page<>(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        // 构建查询条件
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        // 根据员工姓名进行模糊查询，当name不为空时才会加入该条件
        queryWrapper.like(StringUtils.isNotEmpty(employeePageQueryDTO.getName()),
                Employee::getName,
                employeePageQueryDTO.getName());
        // 添加排序条件：按创建时间降序
        queryWrapper.orderByDesc(Employee::getCreateTime);
        // 执行分页查询
        Page<Employee> employeePage = this.page(pageInfo, queryWrapper);
        // 封装结果并返回
        PageResult pageResult = new PageResult(employeePage.getTotal(), employeePage.getRecords());
        return Result.success(pageResult);
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        // 先查询员工是否存在
        Employee existEmployee = this.getById(id);
        if (existEmployee == null) {
            throw new AccountNotFoundException("员工不存在");
        }
        // 使用MyBatis-Plus的Lambda更新构造器
        LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Employee::getId, id)
                .set(Employee::getStatus, status);
//                .set(Employee::getUpdateTime, LocalDateTime.now())
//                .set(Employee::getUpdateUser, BaseContext.getCurrentId());
        // 执行更新操作
        boolean success = this.update(updateWrapper);
        if (!success) {
            throw new RuntimeException("员工状态更新失败");
        }
    }
}
